<?php
/**
 * @author Brian Voss
 */
class GithubController extends Social_Oauth_BaseController {
	/**
	 * @var String 
	 */
	protected $serviceKey = 'github';
	/**
	 * Initialization 
	 */
	public function init()
	{
		parent::init();
	}
	/**
	 * Default Page 
	 */
	public function indexAction()
	{
		$authenticated = $this->isAuthenticated();
		echo $authenticated ? "logged in" : "not logged in";
	}
	/**
	 * Start Google authentication
	 */
	public function startauthAction()
	{
		$clientID	= $this->config->app->clientId;
		$callbackUrl= $this->config->oauth->params->callbackUrl;
		$state		= md5(uniqid(rand(), TRUE)); // CSRF protection
		$this->session->state = $state;
		$permissions = $this->config->oauth->scopes->toArray();
		$permissions = implode(",", $permissions);
		
		// Format the login url
		$loginUrl	= $this->config->oauth->params->requestTokenUrl;
		$loginUrl	.= "?client_id=" . $clientID .
				"&state=" . $state .
				"&redirect_uri=" . $callbackUrl .
				"&scope=" . $permissions;

		$this->getResponse()
			->setRedirect($loginUrl)
			->sendResponse();
	}
	
	/**
	 * Complete Netflix authentication
	 */
	public function finishauthAction()
	{
		$params		= $this->getRequest()->getParams();
		$state		= $params["state"];
		$code		= $params["code"];
		$appId		= $this->config->app->clientId;
		$appSecret	= $this->config->app->consumerSecret;
		$callbackUrl= urlencode($this->config->oauth->params->callbackUrl);

		if (!empty( $this->session->state ) && ( $this->session->state == $state ))
		{
			$accessTokenUrl = $this->config->oauth->params->accessTokenUrl;
			$accessTokenUrl .= "?client_id=" . $appId . 
					"&redirect_uri=" . $callbackUrl . 
					"&client_secret=" . $appSecret . 
					"&code=" . $code;

			$response = file_get_contents($accessTokenUrl);
			$params = null;
			parse_str($response, $params);
			$this->session->token = $params["access_token"];
		}
		else
		{
			// Something went horribly wrong
			exit('Invalid callback request. Cannot continue.');
		}
	}
	/**
	 * Cancel Authentication 
	 */
	public function cancelauthAction()
	{
		// TODO
	}
}